<template>
  <div :class="{ isHidden: loadEnd }">
    <common-head title="购物车" />
    <div class="warp">
      <div class="items">
        <div class="zds" v-if="!items.length">
          <img src="../../assets/shibai1.jpg" alt="" @click="goto" />
        </div>
        <van-swipe-cell v-for="item in items" :key="item.id">
          <div class="item">
            <van-checkbox
              @change="itemSelectedChange(item.key, item.selected)"
              v-model="item.selected"
            />
            <!-- 商品卡片 -->
            <van-card
              :num="item.number"
              :price="item.price"
              :title="item.name"
              :thumb="item.pic"
            >
              <template #footer>
                <van-button
                  @click="delItem(item.key)"
                  type="danger"
                  style="margin-bottom: 10px"
                  size="mini"
                  >删除</van-button
                >
                <!-- 不是所有组件都是有style 他不是html标签 -->
                <van-stepper
                  @change="itemNumChange(item.key, item.number)"
                  v-model="item.number"
                /><!-- 绑定值发生变化触发的事件 -->
              </template>
            </van-card>
          </div>
          <template #right>
            <van-button
              square
              text="删除"
              @click="delItem(item.key)"
              type="danger"
              class="delete-button"
            />
          </template>
        </van-swipe-cell>
      </div>
      <van-submit-bar
        :price="total * 100"
        button-text="提交订单"
        @submit="onSubmit"
      >
        <van-checkbox v-model="allChecked">全选</van-checkbox>
      </van-submit-bar>
    </div>
    <mtabbar />
  </div>
</template>

<script>
import CommonHead from "_components/CommonHead";
import Mtabbar from "_components/Mtabbar";
import {
  fetchCartInfo,
  addItemNumber,
  delCartItem,
  setItemSelected,
} from "_api";
import { getToken } from "_utils";
import { Dialog } from "vant";
export default {
  data() {
    return {
      items: [],
      total: 0,
      loadEnd: true,  //整个页面一开始是显示的
    };
  },
  created() {
    this.fetchShoppingInfo();
  },
  methods: {
    itemSelectedChange(key, selected) {
      // 修改商品选中状态
      setItemSelected({
        key, //参数
        selected,
        token: getToken(),
      }).then((res) => {
        if (res.data.code === 0) {
          this.items = res.data.data.items;
          this.total = res.data.data.price;
        }
      });
    },
    goto() {
      this.$router.replace("/home");
    },
    delItem(key) {
      // 删除方法
      // 删除商品
      Dialog.confirm({/* 确认框 */
        title: "删除商品",
        message: "您确认要删除吗",
      }).then(() => {
        // 点击确认按钮
        delCartItem({
          key, //这是请求参数  key和上面key(value)相同可以省略
          token: getToken(),
        }).then((res) => {
          if (res.data.code === 0) {
            //删除成功重新赋值就行了
            this.items = res.data.data.items;
            this.total = res.data.data.price;
            this.$store.commit('cart/set_items',this.items)//购物车数量变成items数量
          }
          if (res.data.code === 700) {
            // 购物车空了
            this.items = [];
            this.total = 0;
            this.$store.commit('cart/set_items',this.items)
          }
        });
      });
    },
    itemNumChange(key, number) {
      // 点击修改购买数量 key购物车记录的key  数量
      addItemNumber({
        key, //参数
        number,
        token: getToken(),
      }).then((res) => {
        if (res.data.code === 0) {
          this.items = res.data.data.items;
          this.total = res.data.data.price;
        }
      });
    },
    onSubmit () {
     // 判断购物车中是否为空 不允许进入订单
      // 拿到所有选中商品
      const checkedItems = this.items.filter(item => item.selected)
      if (this.items.length === 0 || checkedItems.length === 0) {
        Dialog.alert({
          title: '购物车为空',
          message: '当前没有选中商品,请前往选购'
        }).then(() => {
          this.$router.push('/home')
        })
        return false
      }
      // 到订单页
      this.$router.push('/order')
    },
 
    fetchShoppingInfo() {
      //请求购物车商品
      fetchCartInfo({
        token: getToken(),
      }).then((res) => {
        if (res.data.code === 0) {
          this.items = res.data.data.items;
          this.total = res.data.data.price;
        }
        this.loadEnd = false;  //数据删除完
      });
    },
  },
  computed: {
    allChecked: {
      //计算全选的方法
      get() {
        //所有商品选中状态都为true杰哥为true 否则false
        return this.items.every((item) => item.selected); //every数组方法所有都为true才会为true
      },
      set(val) {
        // 点击全选修改 所有单选状态
        // 拿到所有商品的key属性 扔到数组中
        const keys = [];
        this.items.forEach((item) => {
          keys.push(item.key);
        }); //循环全部到一个新数组
        /* console.log(keys) */
        setItemSelected({
          key: keys.join(","),
          selected: val,
          token: getToken(),
        }).then((res) => {
          if (res.data.code === 0) {
            this.items = res.data.data.items;
            this.total = res.data.data.price;
          }
        });
      },
    },
    isShow() {
      return this.items.length;  // 
    },
  },
  components: {
    CommonHead,
    Mtabbar,
  },
};
</script>

<style lang="scss" scoped>
.isHidden {
  visibility: hidden;  
}

.warp {
  padding-bottom: 50px;
  .delete-button {
    height: 100%;
  }
  .item {
    display: flex;
    background: #fafafa;
    .van-checkbox {
      padding: 0 10px;
    }
    .van-card {
      flex: 1; /*撑满空白区域 */
    }
  }
  /deep/ .van-submit-bar {
    bottom: 50px;
  }
}
.zds > img {
  height: 28.22027rem;
  width: 100%;
}
</style>